<template>
  <div class="list">
    <el-card>
      <el-button @click="openUploadDialog" size="medium" type="primary"
        >上传</el-button
      >
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          prop="filename"
          label="视频名称"
          :formatter="formatFileName"
          min-width="250"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="totalSize"
          label="文件大小"
          :formatter="formatFileSize"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="identifier"
          label="文件MD5"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createdAt"
          label="创建时间"
          width="200"
          show-overflow-tooltip
          :formatter="formatDateTime"
        ></el-table-column>
        <el-table-column
          prop="lastUpdatedAt"
          label="最近更新时间"
          width="200"
          show-overflow-tooltip
          :formatter="formatDateTime"
        ></el-table-column>
        <el-table-column label="操作" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleVideoStream(scope.row)"
              >播放</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :title="currentVideoName"
      :visible.sync="dialogVisible"
      width="60%"
      @close="handleClose"
    >
      <video-player
        class="video-player-center-controls"
        id="videoDiv"
        ref="videoPlayer"
        :playsinline="true"
        :options="playerOptions"
        @play="onPlayerPlay($event)"
        @pause="onPlayerPause($event)"
        @ended="onPlayerEnded($event)"
        @waiting="onPlayerWaiting($event)"
        @playing="onPlayerPlaying($event)"
        @loadeddata="onPlayerLoadeddata($event)"
        @timeupdate="onPlayerTimeupdate($event)"
        @canplay="onPlayerCanplay($event)"
        @canplaythrough="onPlayerCanplaythrough($event)"
        @statechanged="playerStateChanged($event)"
        @ready="playerReadied"
      ></video-player>
    </el-dialog>
    <el-dialog
      title="视频上传"
      :visible.sync="uploadDialogVisible"
      width="80%"
      @close="init"
    >
      <VideoView></VideoView>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUploadOk">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import VideoView from "@/views/VideoView.vue";

export default {
  name: "List",
  components: { VideoView },
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      uploadDialogVisible: false,
      audioUrl: null,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0],
        autoplay: false,
        muted: false,
        loop: false,
        controls: true,
        preload: "auto",
        language: "zh-CN",
        aspectRatio: "16:9",
        fluid: true,
        sources: [
          {
            type: "video/mp4",
            src: "",
          },
        ],
        poster: "", // 封面地址
        width: document.documentElement.clientWidth,
        notSupportedMessage: "加载中......", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
      currentVideoName: "视频播放",
      currentTime: null,
      totalTime: null,
      fileId: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      request
        .get("http://localhost:8888/api/video/list")
        .then((res) => {
          this.tableData = res.data.data;
        })
        .catch((err) => {
          this.$message.error("查询视频列表失败，原因：" + err);
        });
    },
    openUploadDialog() {
      // this.$refs.uploader.open();
      this.uploadDialogVisible = true;
    },
    async handleVideoStream(row) {
      this.fileId = row.fileId;
      this.currentTime = 0;
      // 等待 getProgressRecord 完成后再继续执行
      await this.getProgressRecord(row.fileId);
      // 现在可以安全地使用 this.currentTime
      this.playerOptions.sources[0].src =
        "http://localhost:8888/api/video/download?videoId=" + row.fileId;
      this.dialogVisible = true;
      this.currentVideoName = row.filename.replace(/\.[^/.]+$/, "");
    },
    formatDateTime(row, column, cellValue) {
      if (!cellValue) return "";
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    formatFileName(row, column, cellValue) {
      return cellValue.replace(/\.[^/.]+$/, "");
    },
    formatFileSize(row, column, cellValue) {
      if (cellValue / 1024 / 1024 / 1024 > 1) {
        return (cellValue / 1024 / 1024 / 1024).toFixed(2) + "GB";
      }
      return cellValue / 1024 / 1024 > 1
        ? (cellValue / 1024 / 1024).toFixed(2) + "MB"
        : (cellValue / 1024).toFixed(2) + "KB";
    },
    onPlayerPlay(e) {
      this.isplay = true;
    },
    onPlayerPause(e) {
      this.currentTime = e.currentTime();
      this.isplay = false;
      this.saveProgressRecord(this.currentTime);
    },
    onPlayerEnded(e) {
      this.isplay = false;
      this.saveProgressRecord(0);
    },
    onPlayerWaiting(e) {
      // todo
    },
    onPlayerPlaying(e) {
      this.currentTime = e.currentTime;
      this.isplay = true;
    },
    onPlayerLoadeddata(e) {
      // e.duration() 可获取视频的总时长
      console.log(e)

      this.totalTime = e.duration();
    },
    onPlayerTimeupdate(e) {
      console.log((e.volume() * 100).toFixed(2) * 1);
    },
    onPlayerCanplay(player) {
      // console.log('player Canplay!', player)
    },
    onPlayerCanplaythrough(player) {
      // console.log('player Canplaythrough!', player)
    },
    playerStateChanged(e) {
      // e.timeupdate 存在时视频正在播放中，e.timeupdate 值为当前播放时间
      // e.pause 存在时视频为暂停状态
      // e.play 存在时视频为播放状态
    },
    playerReadied(player) {
      this.myPlayer = player;
      console.log("this.currentTime:",this.currentTime)
      this.myPlayer.currentTime(this.currentTime ? this.currentTime : 0)
    },
    handleClose() {
      if (this.myPlayer) {
        this.myPlayer.pause();
      }
    },
    handleUploadOk() {
      this.uploadDialogVisible = false;
      this.init();
    },
    saveProgressRecord(currentTime) {
      request
        .post("http://localhost:8888/api/video/record", {
          fileId: this.fileId,
          currentTime: currentTime,
          totalTime: this.totalTime
        })
        .then((res) => {
        })
        .catch((err) => {
          this.$message.error("保存视频进度失败，原因：" + err);
        });
    },
    async getProgressRecord(id) {
      try {
        const res = await request.get("http://localhost:8888/api/video/record?fileId=" + id);
        console.log("res.data.data : ", res.data.data);
        if (res.data.data != null) {
          this.currentTime = res.data.data.currentTime;
        }
      } catch (err) {
        this.$message.error("查询视频进度失败，原因：" + err);
      }
    },
  },
};
</script>

<style lang="less">
.list {
  padding: 20px;
}

.video-player-center-controls .vjs-big-play-button {
  left: 50% !important;
  top: 50% !important;
  transform: translate(-50%, -50%);
}

.video-player-center-controls {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dialog {
  margin-top: 5vh !important;
}

.video-js.vjs-ended .vjs-big-play-button,
.video-js.vjs-paused .vjs-big-play-button,
.vjs-paused.vjs-has-started.vjs-custom-skin > .video-js .vjs-big-play-button {
  display: block;
  background: transparent;
  border-color: transparent;
}

.video-js:hover .vjs-big-play-button,
.vjs-custom-skin > .video-js .vjs-big-play-button:focus,
.vjs-custom-skin > .video-js .vjs-big-play-button:active {
  display: block;
  background: transparent !important;
  border-color: transparent !important;
}

.video-js .vjs-big-play-button:hover .vjs-icon-placeholder:before {
  color: white;
}

.video-js .vjs-big-play-button .vjs-icon-placeholder:before {
  color: rgba(255, 255, 255, 0.29);
}
</style>